﻿using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Admin.Web.Models;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;
using Admin.Model.ResponseModel;
using Admin.IService;

namespace Admin.Web.Controllers.Router
{
    public class HomeController : BaseController
    {
        private readonly ILogger<HomeController> _logger;
        private ISysMenuService _sysMenuService;

        public HomeController(ILogger<HomeController> logger, ISysMenuService sysMenuService)
        {
            _logger = logger;
            _sysMenuService = sysMenuService;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>

        public ActionResult DashBord()
        {
            return Content("首页");
        }

        /// <summary>
        /// 动态生成权限菜单列表
        /// 该方法在action之前执行
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string Name = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.Name).FirstOrDefault().Value;
            string Account = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
            var list = await _sysMenuService.QueryMenu(new { Account, Name }, "u.Account=@Account and u.Name=@Name");
            string html = "";
            foreach (ResponseMenu menus in list)
            {
                html = $"{html}<li>";
                html = $"{html}<a href='#'><i class='{menus.Icon}'></i><span class='nav-label'>{menus.Name}</span><span class='fa arrow'></span></a>";

                if (menus.Menus.Count > 0)
                {
                    html = $"{html}<ul class='nav nav-second-level'>";
                    foreach (Menu menu in menus.Menus)
                    {
                        html = $"{html}<li><a class='menuItem' href='{menu.Url}'>{menu.Name}</a></li>";
                    }
                    html = $"{html}</ul></li>";
                }
                else
                {
                    html = $"{html}</li>";
                }
            }
            ViewBag.html = html;
            await next();
        }



        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
